package com.tsd.core.aspect;

import cn.hutool.db.Entity;
import com.tsd.core.annotation.CheckVersion;
import com.tsd.core.constants.VersionConstants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.version.VersionUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName: CheckVersionAspect
 * @Description: 检查版本切面
 * @Author: Hillpool
 * @Date: 2024/4/22 14:04
 * @Version: 1.0
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
@Aspect
@Component
public class CheckVersionAspect {

    public static final Logger LOGGER = LoggerFactory.getLogger(CheckVersionAspect.class);

    @Pointcut("@annotation(checkVersion)")
    public void pointcut4Annotation(CheckVersion checkVersion) {
    }

    @Pointcut("execution(* com.tsd..controller.*.*(..))")
    public void pointcut4Controller() {
    }

    @Around(value = "pointcut4Annotation(checkVersion)", argNames = "joinPoint,checkVersion")
    public Object around4Annotation(ProceedingJoinPoint joinPoint, CheckVersion checkVersion) throws Throwable {
        if (checkVersion == null) {
            return joinPoint.proceed();
        }
        return this.checkVersion(joinPoint, checkVersion);
    }

    @Around(value = "pointcut4Controller()")
    public Object around4Controller(ProceedingJoinPoint joinPoint) throws Throwable {
        CheckVersion checkVersion = AspectUtil.getAannotation(joinPoint, CheckVersion.class);
        if (checkVersion != null) {
            return joinPoint.proceed();
        }
        return this.checkVersion(joinPoint, null);
    }



    /**
     * 检查版本是否匹配账套版本
     *
     * @param joinPoint
     * @param version
     * @return
     * @throws Throwable
     */
    private Object checkVersion(ProceedingJoinPoint joinPoint, CheckVersion version) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String requestURL = AspectUtil.getRequestURL(joinPoint);
        String requestVersion;
        if (version != null) {
            requestVersion = version.version();
        } else {
            requestVersion = VersionUtil.verifyVersion(requestURL);
            if (requestVersion == null) {
                requestVersion = VersionConstants.MODULE_VERSION_FREE;
            }
        }
        Integer requestVersionInt = VersionConstants.getVersionValue(requestVersion);
        String accountSetVersion = VersionConstants.getAccountSetVersion();
        Integer accountSetVersionInt = VersionConstants.getVersionValue(accountSetVersion);
        LOGGER.info("检查版本，当前账套：{}，账套版本：{}，请求URL：{}，请求URL版本：{}",
                DataSourceContextHolder.getDataSourceType(), accountSetVersion, requestURL, requestVersion);
        if (requestVersionInt != null && accountSetVersionInt < requestVersionInt) {
            return HttpResult.fail(ErrorCode.CODE_MISMATCH_VERSION, String.format("该功能属于%s，请先升级版本再使用", VersionConstants.getVersionName(requestVersion)));
        }
        return joinPoint.proceed();
    }
}
